/**
 * Created by George on 2018/3/18.
 */

import util from "../common/util"

// 将本控制器函数作为结果返回给router.js
var noteCtrl = function ($scope, $http) {
    $scope.welcome_info = "笔记管理";
    $scope.noteListDatas = [];
    $scope.emptyHtml = "<div>内容为空</div>";
    $scope.pageItems = [5, 10, 20, 30, 50, 100];
    $scope.pageInfo = {
        pageNo: 1,
        pageSize: 20,
        totalCnt: 0,
        pageNum: 1
    };
    $scope.$emit('updateRoute', 'note');


    $scope.deleteNote = function (data) {
        var msg = "您真的确定要删除吗？";
        if (!confirm(msg)) {
            return;
        }
        console.log(data);
        $http.delete('/basketballfire/rest/note?id=' + data.id, data).then(function () {
            console.log("success!");
            alert("删除成功！");
            initOrUpdateData();
        }, function () {
            console.log("failed!");
            alert("删除成功！");
        });
    };

    function init() {
        $scope.noteListDatas = [];
        initOrUpdateData();
    }

    function initOrUpdateData() {
        $http.get("/basketballfire/rest/note/list", {params: $scope.pageInfo}).then(function (data) {
            console.log(data);
            $scope.pageInfo.totalCnt = data.data.totalCnt;
            $scope.pageList = [];
            var pageNum = Math.ceil($scope.pageInfo.totalCnt / $scope.pageInfo.pageSize); //分页数
            for (var index = 0; index < pageNum; index++) {
                $scope.pageList.push(index + 1);
            }
            $scope.pageInfo.pageNum = pageNum;
            var notesData = data.data.data;
            $scope.noteListDatas = [];
            for (var i = 0; i < notesData.length; i++) {
                var tmpNote = notesData[i];
                var note = {
                    id: tmpNote.id,
                    name: tmpNote.name,
                    content: tmpNote.content || $scope.emptyHtml,
                    date: tmpNote.date,
                    createTime: util.getFormatDate(tmpNote.createTime),
                    lastUpdateTime: util.getFormatDate(tmpNote.lastUpdateTime)
                };
                $scope.noteListDatas.push(note);
            }

        });
    }

    $scope.isActivePage = function (page) {
        return page === $scope.pageInfo.pageNo;
    };

    $scope.selectPage = function (pageNo, pageSize) {
        $scope.pageInfo.pageNo = pageNo;
        $scope.pageInfo.pageSize = pageSize;
        initOrUpdateData();
    };

    //app start
    init();
};

export default noteCtrl;